package com.gitee.neuray.security.admin.staff.biz;

import com.ace.cache.api.impl.CacheRedis;
import com.alibaba.fastjson.JSONObject;
import com.gitee.neuray.security.admin.util.wechat.Dictionary;
import com.gitee.neuray.security.admin.util.wechat.HttpUtil;
import com.gitee.neuray.security.admin.util.wechat.entity.AccessToken;
import com.gitee.neuray.security.admin.util.wechat.entity.UserInfo;
import com.gitee.neuray.security.admin.util.wechat.entity.UserInfoDetail;
import com.gitee.neuray.security.admin.util.wechat.entity.WechatError;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 微信企业号服务层
 */
@Service
public class WechatBiz {

    private static Logger logger = Logger.getLogger(WechatBiz.class);

    @Autowired
    private CacheRedis cacheRedis;

    /**
     * 获取微信企业号accessToken
     *
     * @return
     */
    public AccessToken getAccessToken(String state) {

        AccessToken accessToken = new AccessToken();

        //判断缓存中是否存在accessToken（有效期60分钟）
        //将获取的token存入缓存，设置有效期60分钟
        String tokenCache = "";
        if("wb".equals(state)){
            tokenCache = cacheRedis.get("wbAccessToken");
        }else{
            tokenCache = cacheRedis.get("staffAccessToken");
        }
        //如果存在，则直接返回accessToken
        if (tokenCache!= null &&!tokenCache.isEmpty()) {
            return JSONObject.parseObject(tokenCache,AccessToken.class);
        }

        //如果不存在调用微信企业号获取accesstoken接口，获取token
        CloseableHttpClient client = HttpUtil.getHttpClient();
        //todo 不同应用使用不同的应用密钥，根据自定义参数state获取
        String corpSecret = "";
        if("wb".equals(state)){
            corpSecret = Dictionary.WB_CORPSECRET;
        }else{
            corpSecret = Dictionary.CORPSECRET;
        }
        HttpGet request = new HttpGet(String.format(Dictionary.GET_ACCESS_TOKEN_URL, Dictionary.CORPID,
                corpSecret));
        try (CloseableHttpResponse response = client.execute(request)) {
            String responseContent = new BasicResponseHandler().handleResponse(response);
            WechatError error = JSONObject.parseObject(responseContent, WechatError.class);
            if (error.getErrCode() != 0) {
                throw new Exception(error.toString());
            }
            accessToken = JSONObject.parseObject(responseContent, AccessToken.class);
            accessToken.setTime(System.currentTimeMillis());

            //将获取的token存入缓存，设置有效期60分钟
            if("wb".equals(state)){
                cacheRedis.set("wbAccessToken",JSONObject.toJSONString(accessToken),Dictionary.ACCESS_TOKEN_TIMEOUT_MIN);
            }else{
                cacheRedis.set("staffAccessToken",JSONObject.toJSONString(accessToken),Dictionary.ACCESS_TOKEN_TIMEOUT_MIN);
            }

            logger.info(accessToken.getAccessToken());
            return accessToken;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取微信人员信息
     *
     * @param code
     * @param accessToken
     * @return
     */
    public UserInfo getUserInfo(String code, String accessToken) {
        //调用微信企业号获取人员信息接口
        CloseableHttpClient client = HttpUtil.getHttpClient();
        HttpGet request = new HttpGet(String.format(Dictionary.GET_USER_INFO_URL, accessToken, code));
        try (CloseableHttpResponse response = client.execute(request)) {
            String responseContent = new BasicResponseHandler().handleResponse(response);
            WechatError error = JSONObject.parseObject(responseContent, WechatError.class);
            if (error.getErrCode() != 0) {
                throw new Exception(error.toString());
            }
            UserInfo userInfo = JSONObject.parseObject(responseContent, UserInfo.class);
            userInfo.setTime(System.currentTimeMillis());

            logger.info(userInfo.getUserId());
            return userInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取微信人员信息详情
     *
     * @param userId
     * @param accessToken
     * @return
     */
    public UserInfoDetail getUserInfoDetail(String userId, String accessToken) {
        //调用微信企业号获取人员信息接口
        CloseableHttpClient client = HttpUtil.getHttpClient();
        HttpGet request = new HttpGet(String.format(Dictionary.GET_USER_INFO_DETAIL_URL, accessToken, userId));
        try (CloseableHttpResponse response = client.execute(request)) {
            String responseContent = new BasicResponseHandler().handleResponse(response);
            WechatError error = JSONObject.parseObject(responseContent, WechatError.class);
            if (error.getErrCode() != 0) {
                throw new Exception(error.toString());
            }
            UserInfoDetail userInfo = JSONObject.parseObject(responseContent, UserInfoDetail.class);
            userInfo.setTime(System.currentTimeMillis());

            logger.info(userInfo.getUserId());
            return userInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
